package com.hujiang.basic.search.handler.impl;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.MultiSearchRequestBuilder;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;

import com.hujiang.basic.framework.core.util.DateUtil;

public class ESTest2 {

    public static void main(String[] args) throws UnknownHostException {
        Client client = TransportClient.builder().build()
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.36.167"), 9300));
        List<Map<String, Object>> datas = new ArrayList<>(50100);

        ESTest2 test = new ESTest2();
        long begin = System.currentTimeMillis();
        for (int i = 50000; i < 100000; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("user", i);
            map.put("tags", Arrays.asList("很帅", "无敌", "老王").toString());
            map.put("update_date", DateUtil.nowDate("yyyy-MM-dd'T'HH:mm:ss"));
            datas.add(map);
        }
        test.addDocuments(client, datas, "crm", "tag");

        // CountDownLatch cdl = new CountDownLatch(50000);
        // for(int i= 0; i<50000; i++){
        // final String aa = String.valueOf(i);
        // exector.submit(new Callable<String>() {
        // @Override
        // public String call() throws Exception {
        // test.queryDocuments(client, "crm", "tag", "user", aa);
        // test.deleteDocument(client, "crm", "tag", aa);
        // test.updateDocument(client, "crm", "tag", aa);
        // cdl.countDown();
        // return "";
        // }
        // });
        // }

        // try {
        // cdl.await();
        // } catch (InterruptedException e) {
        // e.printStackTrace();
        // }

        // for(int i=0; i<50000; i++){
        // Map<String, Object> map = new HashMap<>();
        // map.put("user", i);
        // datas.add(map);
        // }

        System.out.println(System.currentTimeMillis() - begin);
    }

    public void deleteDocument(Client client, String index, String type, String id) {
        // 删除_id为1的类型
        client.prepareDelete(index, type, id).get();
        System.out.println(id);
    }

    public void updateDocument(Client client, String index, String type, String id) throws IOException {
        client.prepareUpdate(index, type, id).setDoc(XContentFactory.jsonBuilder().startObject()
                .field("tags", Arrays.asList("老王", "上海", "隔壁").toString()).endObject()).get();
        System.out.println(id);
    }

    public void addDocuments(Client client, List<Map<String, Object>> list, String index, String type) {
        try {

            BulkRequestBuilder bulkRequest = client.prepareBulk();

            for (Map<String, Object> map : list) {
                // 遍历map所有field,构造插入对象
                XContentBuilder xb = XContentFactory.jsonBuilder().startObject();
                String userId = null;
                for (String key : map.keySet()) {
                    xb.field(key, map.get(key));
                    if (key == "user") {
                        userId = map.get(key) + "";
                    }
                }
                xb.endObject();
                // id尽量为物理表的主键
                bulkRequest.add(client.prepareIndex(index, type, userId).setSource(xb));
            }
            BulkResponse bulkResponse = bulkRequest.execute().actionGet();
            if (bulkResponse.hasFailures()) {
                System.err.println("");
            }
            bulkRequest.request().requests().clear();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void queryDocuments(Client client, String index, String type, String key, String value) {
        SearchResponse response = client.prepareSearch(index)// 可以同时搜索多个索引prepareSearch("index","index2")
                .setTypes(type)// 可以同时搜索多个类型
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(QueryBuilders.termQuery(key, value)) // Query
                .setSize(1).execute().actionGet();
        System.out.println(response.getHits().getAt(0).getSource());
    }

    public long rearch(Client client, List<Map<String, Object>> datas) {
        MultiSearchRequestBuilder msbuilder = client.prepareMultiSearch();
        for (Map<String, Object> map : datas) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                SearchRequestBuilder srb = client.prepareSearch()
                        .setQuery(QueryBuilders.matchQuery(entry.getKey(), entry.getValue())).setSize(1);
                msbuilder.add(srb);
            }
        }

        MultiSearchResponse sr = msbuilder.execute().actionGet();

        long nbHits = 0;
        for (MultiSearchResponse.Item item : sr.getResponses()) {
            SearchResponse response1 = item.getResponse();
            // forSearchResponse(response1);
            nbHits += response1.getHits().getTotalHits();
        }
        return nbHits;
    }

    public void forSearchResponse(SearchResponse response) {
        for (SearchHit hit1 : response.getHits()) {
            System.out.println(hit1.getSource().toString());
        }
    }
}
